package com.shqcjd.yunweiyanoperator.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCustomSignerCredentialProvider;
import com.alibaba.sdk.android.oss.common.utils.OSSUtils;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.ResumableUploadRequest;
import com.alibaba.sdk.android.oss.model.ResumableUploadResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.pojo.VideoCategory;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.AlbumUtils;
import com.shqcjd.yunweiyanoperator.util.MyGlideEngine;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.UIUtils;
import com.shqcjd.yunweiyanoperator.widget.ProgressBarView;
import com.shqcjd.yunweiyanoperator.widget.TagLayout;
import com.shqcjd.yunweiyanoperator.widget.TagTextView;
import com.shqcjd.yunweiyanoperator.widget.ZLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class UploadFileActivity extends BaseActivity {
    @BindView(R.id.btn_finish)
    ImageView btnFinish;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_upload_img)
    ImageView ivUploadIUmg;
    @BindView(R.id.progress_bar_view)
    ProgressBarView progressBarView;
    @BindView(R.id.iv_upload_camera)
    ImageView ivUploadCamera;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.iv_upload_delete)
    ImageView ivUploadDelete;
    @BindView(R.id.tl_dialog_share)
    TagLayout tlDialogShare;
    @BindView(R.id.et_dialog_share_remark)
    EditText etDialogShareRemark;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.et_upload_title)
    EditText etUploadTitle;

    private List<VideoCategory> videTypeList = new ArrayList<>();
    private String mTypeId = "0";

    private Context context;
    private static String FILE_PATH = "";
    private String bucketName = "yunweiyantest1";
    private String accessKeyId = "LTAI3NKY9piGydAN";
    private String accessKeySecret = "TbaGC4PExXlkIH6u48RZeaRGVxDNzF";
    private String endPoint = "http://oss-cn-shanghai.aliyuncs.com";

    private final int IMAGE_FILE_RESULT_CODE = 777;
    private String mFileName = "";
    private int mProgress = 0;
    private String successUrl = "";

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_upload_file;
    }

    @Override
    public void initView() {
        super.initView();
        context = this;
        tvTitle.setText("上传视频");

        FILE_PATH = PrefUtils.getString(context, PrefUtils.UPLOAD_VIDEO_URI, "");
        if(!FILE_PATH.equals("")){
            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.ic_default_small)    //加载成功之前占位图
                    .error(R.mipmap.ic_default_small);//指定图片的缩放类型为centerCrop （等比例缩放图片，直到图片的宽高都
            Glide.with(context)
                    .load(FILE_PATH)
                    .apply(options)
                    .thumbnail(0.1f)
                    .into(ivUploadIUmg);
            ivUploadIUmg.setVisibility(View.VISIBLE);
            ivUploadCamera.setVisibility(View.INVISIBLE);
            ivUploadDelete.setVisibility(View.VISIBLE);
            mFileName = getObjectFileKey(FILE_PATH);
            etUploadTitle.setText(mFileName);
            mProgress = PrefUtils.getInt(context, PrefUtils.UPLOAD_VIDEO_PROCESS, 0);
            progressBarView.setProgress(mProgress);
            successUrl = "https://"+bucketName+".oss-cn-shanghai.aliyuncs.com/"+mFileName;
        }
        getVodepCategoryHttp();

    }

    private void getVodepCategoryHttp(){
        ApiService.getVideoCategory()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<VideoCategory>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<VideoCategory>> retData) {
                        if (retData.retCode == 10000) {
                            videTypeList = retData.data;
                            setVideoData();
                        } else {
                            ToastUtils.showShort(context,retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(context,errorMessage);
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                    }
                });
    }


    private void uploadVideoHttp(){
        Map<String, String> map = new HashMap<>();
        map.put("title", etUploadTitle.getText().toString().trim());
        map.put("url", successUrl + "");
        map.put("videoCategoryId", mTypeId + "");
        if(mTypeId.equals("-1")){
           String remark = etDialogShareRemark.getText().toString();
           map.put("videoCategoryName", remark);
        }
        ApiService.addVideo(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData.retCode == 10000) {
                            ToastUtils.showShort(context, "上传成功");
                            cleanUpload();
                            finish();
                        } else {
                            ToastUtils.showShort(context,retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(context,errorMessage);
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                    }
                });
    }



    public void setVideoData(){
        String[] tagText = new String[videTypeList.size()+1];
        tagText[0] = "";
        for(int i=1; i<videTypeList.size()+1; i++){
            tagText[i] = videTypeList.get(i-1).name;
        }
        addTag(tlDialogShare, tagText);
    }


    public void RequestLocationAndCallPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Matisse.from(UploadFileActivity.this)
                                    .choose(MimeType.ofVideo()) // 选择 mime 的类型
                                    .countable(false)
                                    .maxSelectable(1) // 图片选择的最多数量
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f) // 缩略图的比例
                                    .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                                    .theme(R.style.Matisse_Zhihu)
//                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(true, getPackageName()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .forResult(IMAGE_FILE_RESULT_CODE); // 设置作为标记的请求码
                        } else {

                        }
                    }
                });
    }




    @OnClick({R.id.btn_finish, R.id.iv_upload_camera, R.id.tv_start, R.id.iv_upload_delete, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                finish();
                break;
            case R.id.iv_upload_camera:
                RequestLocationAndCallPermission();
                break;
            case R.id.tv_start:
                if(mProgress==100){
                    ToastUtils.showShort(context, "视频已经上传成功");
                    return;
                }
                if(!FILE_PATH.equals("")){
                    if(tvStart.getText().equals("开始")){
                        tvStart.setText("暂停");
                        tvStart.setBackgroundResource(R.mipmap.video_upload_pause_img);
                        upload();
                    }else{
                        tvStart.setText("开始");
                        tvStart.setBackgroundResource(R.mipmap.video_upload_start_img);
                        if (task!=null){
                            task.cancel();
                        }
                    }
                }else{
                    ToastUtils.showShort(context, "请先上传视频");
                }
                break;
            case R.id.iv_upload_delete:
                ivUploadCamera.setVisibility(View.VISIBLE);
                ivUploadDelete.setVisibility(View.INVISIBLE);
                ivUploadIUmg.setVisibility(View.INVISIBLE);
                cleanUpload();
                break;
            case R.id.tv_commit:
                if(mProgress==100){
                    if(!mTypeId.equals("0")){
                        if(mTypeId.equals("-1")&&etDialogShareRemark.getText().toString().equals("")){
                            ToastUtils.showShort(context, "请添加备注");
                            return;
                        }
                        if(!etUploadTitle.getText().toString().trim().equals("")){
                            if(UIUtils.isFastClick()){
                                uploadVideoHttp();
                            }
                        }else{
                            ToastUtils.showShort(context, "视频标题不能为空");
                        }
                    }else{
                        ToastUtils.showShort(context, "分类不能为空");
                    }
                }else{
                    ToastUtils.showShort(context, "请上传视频");
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_FILE_RESULT_CODE && resultCode == RESULT_OK) {
            //图片上传
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    try {
                        String albumStringPath = AlbumUtils.getRealFilePath(this, uri);
                        FILE_PATH = albumStringPath;
                        mFileName = getObjectFileKey(albumStringPath);
                        PrefUtils.setString(context, PrefUtils.UPLOAD_VIDEO_URI, albumStringPath);
                        RequestOptions options = new RequestOptions()
                                .placeholder(R.mipmap.ic_default_small)    //加载成功之前占位图
                                .error(R.mipmap.ic_default_small);//指定图片的缩放类型为centerCrop （等比例缩放图片，直到图片的宽高都
                        Glide.with(context)
                                .load(albumStringPath)
                                .apply(options)
                                .thumbnail(0.1f)
                                .into(ivUploadIUmg);
                        ivUploadCamera.setVisibility(View.INVISIBLE);
                        ivUploadDelete.setVisibility(View.VISIBLE);
                        ivUploadIUmg.setVisibility(View.VISIBLE);
                        etUploadTitle.setText(mFileName);
                        upload();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    private void addTag(final TagLayout tagLayout, String[] tagText) {
        for (int i = 0; i < tagText.length; i++) {
            String t = tagText[i];
            final TagTextView tagView = new TagTextView(context, tagLayout);
            // layout parameters
            ViewGroup.MarginLayoutParams lp;
            if (i == 0) {
                // title
                tagView.setTextColor(0xff333333);
                tagView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);

                lp = new ZLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);

            } else {
                tagView.setEllipsize(TextUtils.TruncateAt.END);
                tagView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                tagView.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.background_tag));
                tagView.setTextColor(Color.parseColor("#666666"));
                tagView.setPadding(25, 15, 25, 15);
                tagView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tagView.setChecked(!tagView.isChecked());
                        if(tagLayout.value().equals("其它  ")){
                            etDialogShareRemark.setVisibility(View.VISIBLE);
                        }else{
                            etDialogShareRemark.setVisibility(View.GONE);
                        }
                        if(tagView.isChecked()){
                            mTypeId = videTypeList.get((Integer) tagView.getTag()-1).id;
                        }else{
                            mTypeId = "0";
                        }
                    }
                });

                lp = new ZLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            }
            tagView.setText(t);
            tagView.setTag(i);
            tagView.setSingleLine(true);

            lp.leftMargin = 20;
            lp.topMargin = 10;
            lp.rightMargin = 0;
            lp.bottomMargin = 0;
            tagLayout.addView(tagView, lp);
        }
    }

    private void cleanUpload(){
        if(task!=null){
            task.cancel();
        }
            String recordDirectory = Environment.getExternalStorageDirectory().getAbsolutePath() + "/oss_record/";
            File recordDir = new File(recordDirectory);
            if (recordDir.isDirectory()) {
                 File[] files = recordDir.listFiles();
                 for (int i = 0; i < files.length; i++) {
                     File f = files[i];
                     f.delete();
                  }
              }
        tvStart.setText("开始");
        tvStart.setBackgroundResource(R.mipmap.video_upload_start_img);
        etUploadTitle.setText("");
        mProgress = 0;
        progressBarView.setProgress(mProgress);
        FILE_PATH = "";
        PrefUtils.setString(context, PrefUtils.UPLOAD_VIDEO_URI, "");
        PrefUtils.setInt(context, PrefUtils.UPLOAD_VIDEO_PROCESS, 0);
    }

    OSSAsyncTask task;

    private void upload() {
        tvStart.setText("暂停");
        tvStart.setBackgroundResource(R.mipmap.video_upload_pause_img);
        String objectKey = mFileName;
        if (TextUtils.isEmpty(objectKey)) {
            return;
        }
        String recordDirectory = Environment.getExternalStorageDirectory().getAbsolutePath() + "/oss_record/";
        File recordDir = new File(recordDirectory);
// 要保证目录存在，如果不存在则主动创建
        if (!recordDir.exists()) {
            recordDir.mkdirs();
        }
        ResumableUploadRequest request = new ResumableUploadRequest(bucketName, objectKey, FILE_PATH, recordDirectory);
        //设置false,取消时，不删除断点记录文件，如果不进行设置，默认true，是会删除断点记录文件，下次再进行上传时会重新上传。
        request.setDeleteUploadOnCancelling(false);
        request.setProgressCallback(new OSSProgressCallback<ResumableUploadRequest>() {
            @Override
            public void onProgress(ResumableUploadRequest request, long currentSize, long totalSize) {
                Log.d("GetObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                mProgress = (int) (100 * currentSize / totalSize);
                progressBarView.setProgress(mProgress);
            }
        });
        task = initializationOss().asyncResumableUpload(request, new OSSCompletedCallback<ResumableUploadRequest, ResumableUploadResult>() {
            @Override
            public void onSuccess(ResumableUploadRequest request, ResumableUploadResult result) {
                mProgress = 100;
                progressBarView.setProgress(mProgress);
                successUrl = "https://"+bucketName+".oss-cn-shanghai.aliyuncs.com/"+mFileName;
                PrefUtils.setInt(context, PrefUtils.UPLOAD_VIDEO_PROCESS, mProgress);
                Log.d("GetObject", "onSuccess:--"+successUrl);
            }

            @Override
            public void onFailure(ResumableUploadRequest request, ClientException clientException, ServiceException serviceException) {
                Log.d("GetObject", "onFailure");
                PrefUtils.setInt(context, PrefUtils.UPLOAD_VIDEO_PROCESS, mProgress);
                if (clientException != null) {
                } else if (serviceException != null) {
                }
            }
        });
    }

    public String getObjectFileKey(String path) {
        String[] pathArrays = path.split("/");
        if (pathArrays == null) {
            return null;
        }
        String fileName = pathArrays[pathArrays.length - 1];
        // 一个/表示创建一个文件夹，这里可以根据自己需求改，不需要跟我这一样，我这的需求是把文件上传到Android文件夹下的channelId文件夹里
        return String.format(fileName);
    }

    private OSS initializationOss() {
        // 在移动端建议使用STS方式初始化OSSClient。
        // 更多信息可查看sample 中 sts
        // 使用方式(https://github.com/aliyun/aliyun-oss-android-sdk/tree/master/app/src/main/java/com/alibaba/sdk/android/oss/app)
// OSSCustomSignerCredentialProvider
        OSSCustomSignerCredentialProvider ossCustomSignerCredentialProvider = new OSSCustomSignerCredentialProvider() {

            @Override
            public String signContent(String content) {
                return OSSUtils.sign(accessKeyId, accessKeySecret, content);
            }
        };

        // 该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(5); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(getApplicationContext(), endPoint, ossCustomSignerCredentialProvider);
        return oss;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (task!=null){
            task.cancel();
        }
    }
}
